from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.backstage.models import Admin
from apps.mqtt.models import DHT11
from apps.user.models import User
from utils.response_code import RETCODE
from utils.sun_jwt import JWT_Handler


class Test(View):
    def get(self, request):
        return http.JsonResponse({'code': 'backstage'})


class UserNum(View):
    def get(self, request):
        users = User.objects.all()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '查询成功', 'data': len(users)})


class UserMsg(View):
    def get(self, request):
        users = User.objects.all()
        data = []
        for user in users:
            dict = {}
            dict['name'] = user.name
            dict['sex'] = user.sex
            dict['phone'] = user.phone
            data.append(dict)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '查询成功', 'data': data})


class DHT11Msg(View):
    def get(self, request):
        dht11 = DHT11.objects.all()
        tem_list = []
        hum_list = []
        date_list = []
        for i in range(7):
            tem_list.append(dht11[i].tem)
            hum_list.append(dht11[i].hum)
            date_list.append(dht11[i].date)
        data = [
            tem_list,
            hum_list,
            date_list
        ]
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '获取数据成功', 'data': data})


class AdminLogin(View):
    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        jwt = JWT_Handler()
        try:
            user = Admin.objects.get(username=username)
            _username = user.username
            _password = user.password
            if password == jwt.sun_decode(_password)['data']:
                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '登录成功'})
            else:
                return http.JsonResponse({'code': RETCODE.PWDERR , 'errmsg': '账号或密码错误'})
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.USERERR, 'errmsg': '不存在此用户'})
